package com.fangyahao.role.controller;

import com.fangyahao.role.base.BaseController;
import com.fangyahao.role.service.UserService;
import com.fangyahao.role.service.impl.UserServiceImpl;
import com.fangyahao.role.utils.HttpRequestPost;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "fangyahaoUserController",urlPatterns = "/fangyahao/user")
public class UserController extends BaseController {


    private UserService service = new UserServiceImpl();

    public void doGet(ServletRequest request,ServletResponse response){


    }

    public void doPost(ServletRequest request,ServletResponse response) throws IOException {
        Map postMessage = HttpRequestPost.stringToMap(request);
        String flag = (String) postMessage.get("flag");

        if("login".equals(flag)){
            String phone = (String) postMessage.get("phone");
            String password = (String) postMessage.get("password");

            Map<String, Object> rs = service.loginByPhoneAndPassword(phone,password);

            Integer code = (Integer) rs.get("code");
            if(code==200){
                Integer userId =(Integer) rs.get("userId");
                HttpServletRequest rq = (HttpServletRequest) request;
                HttpSession session = rq.getSession();
                session.setAttribute("userId",userId);

            }
            printData(code==200,(Integer) rs.get("userId"),code,response);
        }

    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse response) throws ServletException, IOException {


        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String method = request.getMethod();

        if(GET_METHOD.equals(method)){
            doGet(request,response);
        }else if(POST_METHOD.equals(method)){
            doPost(request,response);
        }

    }

}
